package org.mii.safeguard_v1.tools.jfreechart;

import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsResultSupport;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.mii.safeguard_v1.Constants;

import com.opensymphony.xwork2.ActionInvocation;

@SuppressWarnings("serial")
public class ChartResult extends StrutsResultSupport {

	private final static String CHART = "chart";
	private final static String WIDTH = "width";
	private final static String HEIGHT = "height";

	// 图片类型 jpg,png
	private String imageType;

	public void setImageType(String imageType) {
		this.imageType = imageType;
	}

	@Override
	protected void doExecute(String arg0, ActionInvocation ai) throws Exception {

		// 获取render成图片的数据 这种方式就规避了图片大小默认要在struts.xml中设置的问题
		JFreeChart chart = (JFreeChart) ai.getStack().findValue(CHART);
		int width = Integer.parseInt(ai.getStack().findValue(WIDTH).toString());
		int height = Integer.parseInt(ai.getStack().findValue(HEIGHT)
				.toString());

		// 获取OutPutStream且设置编码
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding(Constants.ENCODING_CHARSET);
		OutputStream os = response.getOutputStream();

		// 生成不同类型的图片
		if (ChartConstants.IMG_JPEG.equalsIgnoreCase(imageType)
				|| ChartConstants.IMG_JPG.equalsIgnoreCase(imageType))
			ChartUtilities.writeChartAsJPEG(os, chart, width, height);
		else if (ChartConstants.IMG_PNG.equalsIgnoreCase(imageType))
			ChartUtilities.writeChartAsPNG(os, chart, width, height);
		else
			ChartUtilities.writeChartAsJPEG(os, chart, width, height);

		os.flush();
	}

}
